﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using SMG.Domain.Repository.System;
using SMG.Application.DTO.System;
using SMG.Application.Extension;
using SMG.ServiceContract.System;
using Infrastructure.Core.Common;
using SMG.Domain.Repository;
using SMG.Domain.Specifications.System;

namespace SMG.Application.System
{
    /// <summary>
    /// 公共服务实现
    /// </summary>
    public class CommonServiceImpl : ApplicationService, ICommonService
    {
        //系统字典仓储
        ISysDictRepository dictRepository;

        public CommonServiceImpl(IRepositoryContext context, ISysDictRepository dictRepository)
            : base(context)
        {
            this.dictRepository = dictRepository;
            this.dictRepository.SetContext(context);
        }

        /// <summary>
        /// 根据字典key获取字典项
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public SysDictDto GetDictByKey(string key)
        {
            var dict = dictRepository.QueryBy(new DictKeyEqualSpecification(key)).FirstOrDefault();
            return dict.ConvertToDictDto();
        }

        /// <summary>
        /// 添加一个系统字典项
        /// </summary>
        /// <param name="dictDto"></param>
        /// <returns></returns>
        public bool AddDictItem(SysDictDto dictDto)
        {
            if (String.IsNullOrEmpty(dictDto.DictKey))
                throw new ArgumentNullException("字典键{0}不能为空", dictDto.DictKey);

            var dict = GetDictByKey(dictDto.DictKey);
            if (dict != null)
                throw new Exception(String.Format("已经重复存在的字典键{0}", dict.DictKey));

            dictRepository.Create(dictDto.ConvertToDict());
            return Context.Commit();
        }

        /// <summary>
        /// 更新字典项
        /// </summary>
        /// <param name="dictDto"></param>
        /// <returns></returns>
        public bool UpdateDictItem(SysDictDto dictDto) {
            if (String.IsNullOrEmpty(dictDto.DictKey))
                throw new ArgumentNullException("字典键{0}不能为空", dictDto.DictKey);

            var dict = GetDictByKey(dictDto.DictKey);
            if (dict == null)
                throw new Exception(String.Format("无效的字典键{0}", dict.DictKey));

            dictRepository.Update(dictDto.ConvertToDict());
            return Context.Commit();
        }

    }
}
